package activity.addCamera;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.hichip.campro.R;
import com.hichip.sdk.HiChipSDK;
import base.HiActivity;
import bean.MyCamera;
import butterknife.BindView;
import common.A2bigA;
import common.HiDataValue;
import common.TitleView;
import main.MainActivity;
import pub.devrel.easypermissions.EasyPermissions;
import utils.EmojiFilter;
import utils.FullCharUnionFilter;
import utils.HiToast;
import utils.HiTools;
import utils.NotCopyAndPaste;
import zxing.CaptureActivity;

/**
 * 添加摄像机    有扫描二维码获取UID和局域网搜索获取UID 就是正在使用的设备点进来的
 * Created by lt on 2017\12\15 0015.
 */
public class AddCameraActivity extends HiActivity implements View.OnClickListener {
    @BindView(R.id.titleview) TitleView titleview;
    @BindView(R.id.et_add_camera_uid) EditText et_add_camera_uid;
    @BindView(R.id.et_add_camera_username) EditText et_add_camera_username;
    @BindView(R.id.et_add_camera_password) EditText et_add_camera_password;
    @BindView(R.id.ll_scan_getuid) LinearLayout ll_scan_getuid;
    @BindView(R.id.ll_search_getuid) LinearLayout ll_search_getuid;
    private MyCamera camera;
    private String mUid;
    private final static int REQUEST_SCANNIN_GREQUEST_CODE = 1;
    private int mType = 0;  //其实都一样只是 我好区分
    //mType==1  说明就是 声波配置成功(SoundWavesConfigActivity) 跳转过来的。
    //mType==2  说明就是 局域网搜索(LanSearchCameraActivity) 跳转过来的
    //mType==2  说明就是 局域网搜索(CaptrueActivity) 跳转过来的

    @BindView(R.id.tv_confirm_add) TextView tv_confirm_add;
    @BindView(R.id.tv_hint_get_uid) TextView tv_hint_get_uid;


    @Override
    protected int setLayoutId() {
        return R.layout.activity_add_camera;
    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        getIntentData();
        initView();
        setListerners();

    }

    private void getIntentData() {
        mType = getIntent().getIntExtra("type", 0);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            mUid = bundle.getString(HiDataValue.EXTRAS_KEY_UID);
        }
    }

    private void setListerners() {
        ll_scan_getuid.setOnClickListener(this);
        ll_search_getuid.setOnClickListener(this);
        tv_confirm_add.setOnClickListener(this);
    }

    private void initView() {
        titleview.setButton(TitleView.NAVIGATION_BUTTON_LEFT);
        titleview.setRightTxtBack(R.mipmap.x_bule);
        titleview.setTitle(getString(R.string.add_device));
        titleview.setNavigationBarButtonListener(new TitleView.NavigationBarButtonListener() {
            @Override
            public void OnNavigationButtonClick(int which) {
                switch (which) {
                    case TitleView.NAVIGATION_BUTTON_LEFT:
                        AddCameraActivity.this.finish();
                        break;
                    case TitleView.NAVIGATION_BUTTON_IV_RIGHT:
                        Intent intent=new Intent(AddCameraActivity.this,MainActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent,true);
                        break;
                }
            }
        });

        et_add_camera_password.setCustomSelectionActionModeCallback(new NotCopyAndPaste());
        et_add_camera_password.setFilters(new InputFilter[] { new InputFilter.LengthFilter(63), new FullCharUnionFilter(AddCameraActivity.this), new EmojiFilter() });
        et_add_camera_username.setCustomSelectionActionModeCallback(new NotCopyAndPaste());
        et_add_camera_username.setFilters(new InputFilter[] { new InputFilter.LengthFilter(63), new FullCharUnionFilter(AddCameraActivity.this), new EmojiFilter() });

        //UID 编辑框自动转换为大写
        et_add_camera_uid.setTransformationMethod(new A2bigA());
        if (!TextUtils.isEmpty(mUid)) {
            et_add_camera_uid.setText(mUid);
            et_add_camera_uid.setEnabled(false);
        }
        if (mType == 1 || mType == 2 || mType == 4) {
            ll_scan_getuid.setVisibility(View.GONE);
            ll_search_getuid.setVisibility(View.GONE);
            tv_hint_get_uid.setVisibility(View.GONE);
        }
    }

    private final static int REQUESTCODE_SCANGETUID = 110;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_scan_getuid://二维码扫描获取UID
                String[] perms = {Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE};
                if(EasyPermissions.hasPermissions(this,perms)){
                    Intent intent=new Intent(AddCameraActivity.this, CaptureActivity.class);
                    intent.putExtra("category", 3);
                    startActivityForResult(intent, REQUESTCODE_SCANGETUID);
                }
                break;
            case R.id.ll_search_getuid://局域网搜索获取UID
                if (HiTools.isWifiConnected(AddCameraActivity.this)) {
                    Intent intent = new Intent(AddCameraActivity.this, LANSearchCameraActivity.class);
                    intent.putExtra("type", 3);
                    startActivity(intent);
                } else {
                    HiToast.showToast(AddCameraActivity.this, getString(R.string.toast_connect_wifi));
                }
                break;
            case R.id.tv_confirm_add://确认添加
                chickDone();
                break;
        }
    }

    private void handScan() {
        boolean isGranted = ContextCompat.checkSelfPermission(AddCameraActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
        if (HiDataValue.ANDROID_VERSION >= 6 && isGranted) {
            Intent intent = new Intent(AddCameraActivity.this, CaptureActivity.class);
            startActivityForResult(intent, REQUEST_SCANNIN_GREQUEST_CODE);
        } else {
            //申请权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 110);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 110:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent(AddCameraActivity.this, CaptureActivity.class);
                    startActivityForResult(intent, REQUEST_SCANNIN_GREQUEST_CODE);
                } else {
                    Toast.makeText(this, getString(R.string.no_permission), Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    private void chickDone() {
        String str_uid = et_add_camera_uid.getText().toString().trim().toUpperCase();
        String str_username = et_add_camera_username.getText().toString();
        String str_password = et_add_camera_password.getText().toString().trim();
        for (int i = 0; i < HiDataValue.zifu.length; i++) {
            if (str_uid.contains(HiDataValue.zifu[i])) {
                Toast.makeText(AddCameraActivity.this, getText(R.string.tips_invalid_uid).toString(), Toast.LENGTH_SHORT).show();
                return;
            }
        }
        if (TextUtils.isEmpty(str_uid)) {
            showAlert(getText(R.string.tips_null_uid));
            return;
        }
        String string = HiTools.handUid(str_uid);
        str_uid = string;
        if (str_uid == null) {
            HiToast.showToast(AddCameraActivity.this, getString(R.string.tips_invalid_uid));
            return;
        }
        if (str_username.length() == 0) {
            showAlert(getText(R.string.tips_null_username));
            return;
        }
        // 解决：用户名和密码同时输入：31个特殊字符，应用后app闪退且起不来
        if (str_username.getBytes().length > 64) {
            HiToast.showToast(AddCameraActivity.this, getString(R.string.tips_username_tolong));
            return;
        }
        if (str_password.getBytes().length > 64) {
            HiToast.showToast(AddCameraActivity.this, getString(R.string.tips_password_tolong));
            return;

        }
        if (HiDataValue.CameraList != null && HiDataValue.CameraList.size() >= 64) {
            HiToast.showToast(AddCameraActivity.this, getString(R.string.tips_limit_add_camera));
            return;
        }
        for (int i = 0; i < HiDataValue.CameraList.size(); i++) {
            MyCamera camera = HiDataValue.CameraList.get(i);
            if (str_uid.equalsIgnoreCase(camera.getUid())) {
                if (ll_scan_getuid.getVisibility() == View.GONE) {//说明就是点击新设备添加的要 覆盖数据库Camera
                    HiDataValue.CameraList.remove(camera);
                } else {
                    showAlert(getText(R.string.tips_add_camera_exists));
                }
                return;
            }
        }
        camera = new MyCamera(getApplicationContext(),getString(R.string.title_camera_fragment), str_uid, str_username, str_password);
        camera.saveInDatabase(this);
        camera.saveInCameraList();
        Intent broadcast = new Intent();
        broadcast.putExtra("mIsAdd", true);
        broadcast.setAction(HiDataValue.ACTION_CAMERA_INIT_END);
        sendBroadcast(broadcast);
        Intent intent=new Intent(AddCameraActivity.this,TakeNameToCamActivity.class);
        intent.putExtra(HiDataValue.EXTRAS_KEY_UID,camera.getUid());
        startActivity(intent);
        HiToast.showToast(this, getString(R.string.add_success));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUESTCODE_SCANGETUID:
                    Bundle extras = data.getExtras();
                    String text = extras.getString(HiDataValue.EXTRAS_KEY_UID).trim();
                    if (!TextUtils.isEmpty(text) && text.length() > 8) {
                        String sub = text.substring(0, 8);
                        if (sub.equalsIgnoreCase(getString(R.string.app_name) + "_AC")) {//二维码是加密分享的UID
                            byte[] datas = text.getBytes();
                            int len = datas.length;
                            HiChipSDK.Aes_Decrypt(datas, len);
                        } else {//二维码是UID
                            et_add_camera_uid.setEnabled(false);
                            et_add_camera_uid.setText(text.toUpperCase());
                        }
                    }
                    break;
            }

        }
    }
}



